<template>
  <div>
    <x-Table
      :loading="loading"
      :table-data="tableData"
      :options-data="options"
      :rule-form="ruleForms"
      :pagination="pagination"
      @handleAdd="handleAdd"
      @handlePaginationCurrentChange="handlePaginationCurrentChange"
      @handlePaginationSizeChange="handlePaginationSizeChange"
      @handleHeardDel="handleHeardDel"
      @searchForm="searchForm"
      @handleHeardEdit="handleHeardEdit"
    >
    </x-Table>
    <!--    弹窗区域-->
    <el-dialog
      v-dialog-drag
      :title="alertTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="45%"
    >
      <form-create
        v-model="fapi"
        :rule="rule"
        :option="option"
        :value.sync="formParam"
        @submit="onSubmit"
      >
      </form-create>
    </el-dialog>
    <!--    end-->
  </div>
</template>

<script>
let _this;
export default {
  data() {
    return {
      loading: true,
      row: null, //当前选择数据
      pagination: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [10, 20, 50, 100],
      }, //分页参数
      otherParam: {
        halfCheckedKeys: [],
      }, //如果有其他情况会拼接这个参数
      fapi: {},
      formParam: {},
      rule: [
        {
          type: "input",
          field: "roleName",
          title: "角色名称",
          info: "",
          props: {
            clearable: true,
          },
          _fc_drag_tag: "input",
          hidden: false,
          display: true,
          validate: [
            {
              type: "string",
              trigger: "submit",
              mode: "required",
              message: "请输入角色名称",
              required: true,
            },
          ],
        },
        {
          type: "inputNumber",
          field: "weight",
          title: "权重",
          info: "",
          props: {
            clearable: true,
            min: 1,
          },
          _fc_drag_tag: "input",
          hidden: false,
          display: true,
          validate: [
            {
              type: "number",
              trigger: "submit",
              mode: "required",
              message: "请输入权重",
              required: true,
            },
          ],
        },
        {
          "type": "tree",
          "field": "permission",
          "title": "权限",
          "info": "",
          "effect": {
            fetch: {
              action:
                "http://www.free.com/adminapi/v1.setting.SystemMenus/getMenusList",
              to: "props.data",
              method: "GET",
              parse(res) {
                function tidy(list) {
                  return list.map((val) => {
                    return {
                      id: val.id,
                      label: val.meta.title,
                      children: val.children ? tidy(val.children) : undefined,
                    };
                  });
                }

                return tidy(res.data);
              },
            },
          },
          "props": {
            "props": {
              "label": "label"
            },
            "showCheckbox": true,
            "nodeKey": "id",
          },
          "_fc_drag_tag": "tree",
          "hidden": false,
          "display": true
        },
        // {
        //   type: "tree",
        //   field: "permission",
        //   title: "权限",
        //   info: "",
        //   on: {
        //     check: function (data, list) {
        //       console.log(list);
        //       _this.otherParam["halfCheckedKeys"] = list.halfCheckedKeys;
        //     },
        //   },
        //   effect: {
        //     fetch: {
        //       action:
        //         "http://www.free.com/adminapi/v1.setting.SystemMenus/getMenusList",
        //       to: "props.data",
        //       method: "GET",
        //       parse(res) {
        //         console.log(res.data)
        //         function tidy(list) {
        //           return list.map((val) => {
        //             return {
        //               id: val.id,
        //               label: val.meta.title,
        //               children: val.children ? tidy(val.children) : undefined,
        //             };
        //           });
        //         }
        //         return tidy(res.data);
        //       },
        //     },
        //   },
        //   props: {
        //     props: {
        //       label: "label",
        //     },
        //     showCheckbox: true,
        //     nodeKey: "id",
        //     data: [],
        //   },
        //   _fc_drag_tag: "tree",
        //   hidden: false,
        //   display: true,
        // },

        {
          type: "input",
          field: "remark",
          title: "备注",
          info: "",
          props: {
            type: "textarea",
          },
          _fc_drag_tag: "input",
          hidden: false,
          display: true,
        },
        {
          type: "switch",
          field: "status",
          title: "状态",
          info: "",
          _fc_drag_tag: "switch",
          hidden: false,
          display: true,
        },
      ],
      option: {
        form: {
          inline: false,
          labelPosition: "right",
          size: "small",
          labelWidth: "125px",
          hideRequiredAsterisk: false,
          showMessage: true,
          inlineMessage: false,
        },
        resetBtn: true,
      },
      dialogVisible: false,
      alertTitle: "添加",
      tableData: [],
      ruleForms: {
        title: {label: "角色名称", prop: "title", type: "text"},
      },
      options: {
        fields: {
          id: {label: "ID", prop: "id", width: "120", order: true},
          name: {label: "角色名称", prop: "title", type: "tag"},
          remark: {label: "备注", prop: "remark"},
          order: {label: "权重", prop: "weight", order: true},
          status: {
            label: "状态",
            prop: "status",
            type: "switch",
            activeValue: true,
            inactiveValue: false,
            switchChage: function (scope) {
            },
          },
          create_time: {label: "创建时间", prop: "create_time", order: true},
          button: {
            label: "操作",
            width: "130",
            type: "func",
            fixed: true,
            edit: function (scope) {
              setTimeout(() => {
                _this.fapi.setValue("roleName", scope["row"].title);
                _this.fapi.setValue("weight", scope["row"].weight);
                _this.fapi.setValue(
                  "permission",
                  scope["row"].rules == null
                    ? scope["row"].rules
                    : scope["row"].rules.split(",")
                );
                _this.fapi.setValue("remark", scope["row"].remark);
                _this.fapi.setValue("status", scope["row"].status);
              }, 0);
              _this.row = scope["row"];
              _this.alertTitle = "编辑";
              _this.dialogVisible = true;
            },
            del: function (scope) {
              _this.delRole(scope["row"].id);
            },
          },
        },
      },
    };
  },
  methods: {
    handlePaginationCurrentChange: function (val) {
      _this.pagination["currentPage"] = val;
      _this.getRoleList();
    },

    handlePaginationSizeChange: function (val) {
      _this.pagination["pageSize"] = val;
      _this.getRoleList();
    },

    /**
     * 获取角色列表
     */
    getRoleList: function () {
      _this.$store
        .dispatch("admin/setRoleList", {
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        })
        .then(() => {
          _this.loading = false;
          _this.dialogVisible = false;
          let data = this.$store.state.admin.roleList;
          this.tableData = data.data;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        });
    },

    /**
     *
     */
    handleHeardEdit: function (val) {
      let scope = val[0];
      _this.row = scope;
      _this.alertTitle = "编辑";
      _this.dialogVisible = true;
      setTimeout(() => {
        _this.fapi.setValue("roleName", scope.title);
        _this.fapi.setValue("weight", scope.weight);
        _this.fapi.setValue(
          "permission",
          scope.rules == null ? scope.rules : scope.rules.split(",")
        );
        _this.fapi.setValue("remark", scope.remark);
        _this.fapi.setValue("status", scope.status);
      }, 0);
    },
    /**
     * 批量删除
     */
    handleHeardDel: function (val) {
      let del = [];
      val.forEach((item, index) => {
        del.push(item.id);
      });
      _this.delRole(del);
    },

    /**
     * 添加角色
     */
    addRole: function (param) {
      _this.$store
        .dispatch("admin/addRoleList", {
          title: param["roleName"],
          status: param["status"],
          pid:
            _this.otherParam["halfCheckedKeys"] == null
              ? ""
              : _this.otherParam["halfCheckedKeys"].join(),
          rules:
            param["permission"] == null
              ? param["permission"]
              : param["permission"].join(),
          weight: param["weight"],
          remark: param["remark"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.$message.success(msg);
            _this.getRoleList();
          } else {
            _this.$message.error(msg);
          }
        });
    },
    /**
     * 表单提交回调
     */
    onSubmit: function (val) {
      if (_this.alertTitle === "添加") {
        _this.addRole(val);
      } else {
        //编辑
        _this.updateRole(val);
      }
    },

    /**
     * 搜索角色标题
     */
    searchForm: function (val) {
      _this.$store
        .dispatch("admin/searchTitle", {
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
          title: val.title,
        })
        .then((res) => {
          _this.dialogVisible = false;
          let data = this.$store.state.admin.roleList;
          this.tableData = data.data;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        });
    },
    /**
     * 更新角色
     */
    updateRole: function (param) {
      _this.$store
        .dispatch("admin/updateRoleList", {
          id: _this.row["id"],
          title: param["roleName"],
          status: param["status"],
          pid:
            _this.otherParam["halfCheckedKeys"] == null
              ? ""
              : _this.otherParam["halfCheckedKeys"].join(),
          rules:
            param["permission"] == null
              ? param["permission"]
              : param["permission"].join(),
          weight: param["weight"],
          remark: param["remark"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getRoleList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     * 删除角色
     */
    delRole: function (val) {
      _this.$store
        .dispatch("admin/delRoleList", {
          id: val,
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getRoleList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     *  表单导航栏添加点击
     */
    handleAdd: function () {
      _this.alertTitle = "添加";
      this.dialogVisible = true;
    },
  },
  watch: {
    dialogVisible(newVal) {
      setTimeout(() => {
        if (!newVal) {
          _this.fapi.resetFields(); //清空数据
        }
      }, 0);
    },
  },
  created() {
    _this = this;
  },
  mounted() {
    this.getRoleList();
  },
};
</script>

<style scoped></style>
